<template>
  <div id="dictManage">
    <!-- <Breadcrumb content="基础字典" /> -->
    <Splitpanes>
      <Pane size="16">
        <!-- 字典分类  -->
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">字典分类</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeloading" @click="findDictTypeList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建根分类" @click="addRootDictTypeDialog()"></vxe-button>
          </template>
        </vxe-toolbar>

        <el-scrollbar style="height: calc(100% - 40px)">
          <div class="sampleType">
            <el-scrollbar>
              <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="dictTypeList" :props="defaultProps" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="treeloading">
                <template #default="{ data, node }">
                  <span>{{ data.name }}</span>
                  <div>
                    <span>
                      <!-- 新增  -->
                      <el-button type="success" class="cirBtn" size="small" icon="Plus" circle @click="appendDictType(data)"></el-button>
                      <!-- 编辑  -->
                      <el-button type="warning" class="cirBtn" size="small" icon="Edit" circle @click="editDictType(data, node)"></el-button>
                      <!-- 删除  -->
                      <el-button type="info" class="cirBtn" size="small" icon="Delete" circle @click="removeDictType(data)"></el-button>
                    </span>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
        </el-scrollbar>

        <!-- 新建/编辑字典分类弹框 -->
        <el-dialog :title="titleClassificationType()" :show-close="false" v-model="showTypeDialog" append-to-body :close-on-click-modal="false" width="500px">
          <el-form ref="dictTypeFormRef" :model="dictTypeForm" :rules="dictTypeFormRule" label-width="100px" class="form-input-m" inline-message>
            <el-form-item prop="pname" label="父级分类" v-if="pnameShow">
              <el-input type="text" v-model="dictTypeForm.pname" placeholder="请输入父类名称" disabled></el-input>
            </el-form-item>
            <el-form-item prop="code" label="编号">
              <el-input type="text" v-model="dictTypeForm.code" placeholder="请输入字典编号" clearable></el-input>
            </el-form-item>
            <el-form-item prop="name" label="名称">
              <el-input type="text" v-model="dictTypeForm.name" placeholder="请输入字典名称" clearable></el-input>
            </el-form-item>
            <el-form-item prop="sx" label="排序" class="input-s">
              <el-input-number v-model="dictTypeForm.sx" :min="0" :max="100" label="请输入顺序号"></el-input-number>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer flex right justify-end">
            <el-button type="primary" @click="saveDictType('dictTypeFormRef')">保存</el-button>
            <el-button @click="closeTypeDialog('dictTypeFormRef')">取消</el-button>
          </div>
        </el-dialog>
      </Pane>

      <Pane size="31">
        <!-- 字典字段  -->
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">字典</div>
            <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findDictList" @keyup="keyupEnter" @search-click="handleSearch(searchForm.searchValue)"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findDictList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addDictDialog()"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-edit" content="设计模式" @click="showDictData()"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-search-zoom-in" content="预览模式" @click="showDetailData()"></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="tableBox">
          <vxe-table ref="dictTable" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="dictList" :loading="tloading" :expand-config="{ expandAll: true, reserve: true }" @current-change="dictRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :keyboard-config="{
              isArrow: true,
              isTab: true,
              isEdit: true
            }" resizable show-overflow keep-source>
            <vxe-column field="code" title="编码" width="100"> </vxe-column>
            <vxe-column field="name" title="名称" width="130"> </vxe-column>
            <vxe-column field="isEdit" title="是否删改" width="180">
              <template #default="{ row, rowIndex, column }">
                <span>{{ row.isEdit === '1' ? '否' : '是' }}</span>
              </template>
            </vxe-column>
            <vxe-column title="操作" fixed="right">
              <template #default="{ row }">
                <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click.native="editDictDialog(row)" class="spanIcon"></vxe-button>
                <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deleteDict(row)" class="spanIcon"></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>

        <!-- 中间字段弹框 -->
        <el-dialog :title="titleType()" :show-close="false" v-model="showDialog" append-to-body width="500px" :close-on-click-modal="false">
          <el-form ref="dictFormRef" :model="dictForm" :rules="dictFormRule" label-width="100px" class="form-input-m" inline-message @reset="resetDictForm">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="code" label="编码">
                  <el-input type="text" v-model="dictForm.code" placeholder="请输入字典编码" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="name" label="名称">
                  <el-input type="text" v-model="dictForm.name" placeholder="请输入字典名称" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否删改" prop="isActive">
                  <el-switch v-model="dictForm.isEdit" inline-prompt active-text="是" inactive-text="否" active-value="0" inactive-value="1"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="order" label="排序">
                  <el-input-number v-model="dictForm.sx" :min="1" :max="1000" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="dialog-footer flex right justify-end">
            <el-button type="primary" @click="saveDict('dictFormRef')">保存</el-button>
            <el-button @click="closeDialog('dictFormRef')">取消</el-button>
          </div>
        </el-dialog>
      </Pane>

      <Pane size="53">
        <DictChildManage ref="dictChildRef" />
      </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang="ts">
// 引入组件区==========
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import type { FormInstance } from 'element-plus';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import DictChildManage from './DictChildManage.vue'; //引用设计模式/字典模式两块/一块内容
import { AppStore } from '../../stores/store';
import { isEmpty } from 'lodash';

// 全局变量定义区 ==========
let store = AppStore();
// 获取模块id
const moduleId = localStorage.getItem('moduleId');
// 功能点权限
let modulePoitPre = reactive([]);
// 通过权限获取功能点
let modulePointMap = store.userInfo.modulePointMap;

// 加载状态
let treeloading = ref(false); //字典分类树上的刷新
let tloading = ref(false); //加载状态

// 弹框表单状态
let showTypeDialog = ref(false); //最左侧字典根分类弹框
const dictTypeFormRef = ref<FormInstance>(); //最左侧的弹框的form
let showDialog = ref(false); //中间字段弹框

// 最左侧的树
let defaultProps = {
  children: 'children',
  label: 'name'
};

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let dictTypeList: any = reactive([]); //最左侧字典分类列表数据
let dictList: any = reactive([]); //中间字典字段table数据
let dictChildRef: any = ref(null); //最右侧点击设计模式/预览模式传值

let pnameShow = ref(false); //父级分类显示
let dictTable = ref(); //中间字段表格
let sltType: any = {};

// 最左侧 新建/编辑字典分类弹框表单
let dictTypeForm = reactive({
  id: null,
  pid: null,
  orgId: '',
  code: '',
  name: '',
  pname: '',
  sx: 1,
  bz: ''
});

// 最左侧字典分类弹框表单校验
let dictTypeFormRule = {
  name: [
    {
      required: true,
      message: '请输入字典名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ]
};

// 中间字典字段的关键字
let searchForm = {
  searchValue: ''
};

// 中间字典字段表单
let dictForm = reactive({
  id: null,
  pid: null,
  orgId: '',
  code: '',
  name: '',
  isEdit: '0',
  grade: 0,
  sx: 0,
  value: '',
  bz: ''
});

// 中间字典字段表单检验
let dictFormRule = {
  name: [
    {
      required: true,
      message: '请输入字段名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findDictTypeList();
});

// 光标定位在指定字典分类上
function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}
// 获取字典分类列表(树) 刷新
function findDictTypeList() {
  treeloading.value = true;
  dictTypeList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictType/findDictTypeTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: {} })
    .then((res: any) => {
      dictTypeList.push(...res.data);
      if (dictTypeList.length > 0) {
        const sltObj = getChildren(dictTypeList[0]);
        sltType = sltObj;
        setCurTypeNode(sltObj.id);
        findDictList();
      }
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取字典分类列表失败', VxeNotifyType.error);
    });
}

// 最左侧 新建字典根分类
function addRootDictTypeDialog() {
  dictTypeForm.pid = 0;
  dictTypeForm.name = '';
  dictTypeForm.code = '';
  pnameShow.value = false;
  if (dictTypeList.length > 0) {
    // 根分类的顺序号
    const sx = dictTypeList[dictTypeList.length - 1].sx + 1;
    dictTypeForm.sx = sx;
  }
  showTypeDialog.value = true;
}

//点击左侧分类
function handleClickType(obj: any, node: any, data: any) {
  sltType = obj;
  findDictList();
}

// 新增字典分类小按钮
function appendDictType(row: any) {
  dictTypeForm.pname = row.name;
  dictTypeForm.pid = row.id;
  dictTypeForm.name = '';
  dictTypeForm.code = '';
  dictTypeForm.sx = 1;
  if (row.children.length > 0) {
    const sx = row.children[row.children.length - 1].sx + 1;
    dictTypeForm.sx = sx;
  } else {
    dictTypeForm.sx = 1;
  }
  pnameShow.value = true;
  showTypeDialog.value = true;
}

// 编辑字典分类小按钮
function editDictType(item: any, node: any) {
  dictTypeForm.pid = item.pid;
  dictTypeForm.id = item.id;
  dictTypeForm.name = item.name;
  dictTypeForm.code = item.code;
  dictTypeForm.sx = item.sx;
  dictTypeForm.pname = node.parent.data.name;
  if (item.pid == 0) {
    pnameShow.value = false;
  } else {
    pnameShow.value = true;
  }
  showTypeDialog.value = true;
}

// 字典分类 新增or保存
function saveDictType(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: dictTypeForm.id,
      pid: dictTypeForm.pid,
      name: dictTypeForm.name,
      code: dictTypeForm.code,
      sx: dictTypeForm.sx,
      orgId: !isEmpty(dictTypeForm.orgId) ? dictTypeForm.orgId : store.userInfo.orgId
    };
    let url = '';
    // 判断添加和编辑接口
    if (dictTypeForm.id) {
      url = '/api/sys/basDictType/editDictType';
    } else {
      url = '/api/sys/basDictType/addDictType';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (dictTypeForm.id) {
            VxeMessage('修改字典成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增字典成功', VxeNotifyType.success);
          }
          findDictTypeList();
          showTypeDialog.value = false;
          // 清空表单
          clearDictTypeForm();
        } else {
          if (dictTypeForm.id) {
            VxeMessage('修改字典失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增字典失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

// 删除字典分类小按钮
function removeDictType(row: any) {
  proxy
    .$confirm('确定删除此分类？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/basDictType/deletDictType';
      if (row.id) {
        if (row.children.length === 0) {
          proxy.$http
            .post(url, row)
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除字典成功', VxeNotifyType.success);
                findDictTypeList();
              } else {
                VxeMessage('删除字典失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除字典异常', VxeNotifyType.error);
            });
        } else {
          VxeMessage('该字典下存在子字典,不能删除', VxeNotifyType.error);
        }
      }
    });
}

// 判断字典分类弹框标题
function titleClassificationType() {
  if (dictTypeForm.id) {
    return `编辑字典分类`;
  } else if (!dictTypeForm.id) {
    return `新建字典分类`;
  }
}

// 字典分类弹框表单清空
function clearDictTypeForm() {
  dictTypeForm.id = null;
  dictTypeForm.pid = null;
  dictTypeForm.pname = '';
  dictTypeForm.code = '';
  dictTypeForm.name = '';
  dictTypeForm.sx = 1;
}

// 字典分类弹框清空校验 关闭弹框
function closeTypeDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();

  dictTypeForm.id = null;
  dictTypeForm.pid = null;
  dictTypeForm.pname = '';
  dictTypeForm.code = '';
  dictTypeForm.name = '';
  dictTypeForm.sx = 1;
  pnameShow.value = false;
  showTypeDialog.value = false;
}

// 中间获取当前字典的字段列表(默认获得全部)
function findDictList() {
  tloading.value = true;
  dictList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDict/findDictPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltType.id, pageIndex: page.currentPage, pageSize: page.pageSize, grade: 0 }
    })
    .then((res: any) => {
      dictList.push(...res.data.records);
      page.totalResult = res.data.total;
      dictRowClick({ row: dictList[0] }); //默认选中第一条数据
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(searchForm.searchValue);
  }
}

// 查询/刷新
function handleSearch(row: string | number) {
  tloading.value = true;
  const url = '/api/sys/basDict/findDictPageList';
  dictList.length = 0;
  proxy.$http
    .get(url, {
      params: { pid: sltType.id, seachValue: row, pageIndex: 1, pageSize: 50, grade: 0 }
    })
    .then((res: any) => {
      dictList.push(...res.data.records);
      page.totalResult = res.data.total;
      dictRowClick({ row: dictList[0] }); //默认选中第一条数据
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}

// 判断中间弹框显示的标题
function titleType() {
  if (dictForm.id) {
    return `编辑字段`;
  } else if (!dictForm.id) {
    return `新建字段`;
  }
}

// 新建一级字典字段
function addDictDialog() {
  dictForm.pid = sltType.id;
  dictForm.sx = page.totalResult + 1;
  showDialog.value = true;
}
// 设计模式
function showDictData() {
  dictChildRef.value.showDictData();
}
// 预览模式
function showDetailData() {
  dictChildRef.value.showDetailData();
}

// 中间编辑当前行字段
function editDictDialog(row: any) {
  dictForm.id = row.id;
  dictForm.pid = row.pid;
  dictForm.orgId = row.orgId;
  dictForm.code = row.code;
  dictForm.name = row.name;
  dictForm.grade = row.grade;
  dictForm.isEdit = row.isEdit;
  dictForm.sx = row.sx;
  dictForm.value = row.value;
  dictForm.bz = row.bz;
  showDialog.value = true;
}

// 中间删除当前行字段
function deleteDict(row: any) {
  proxy
    .$confirm('确定删除此字段？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/basDict/deleteDict';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          findDictList();
          VxeMessage('删除字段成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

// 点击字段当前行触发的事件
function dictRowClick({ row }: any) {
  (proxy.$refs.dictTable as any).setCurrentRow(row);
  dictChildRef.value.initPage(row); //给最右侧传值
}

// 中间字段弹框取消按钮
function closeDialog(formMiddleName: any) {
  const el: any = proxy.$refs[formMiddleName];
  // 移除校验结果
  el.clearValidate();
  clearForm();
  showDialog.value = false;
}
// 清空中间字段弹框表单
function clearForm() {
  dictForm.id = null;
  dictForm.pid = '';
  dictForm.orgId = '';
  dictForm.code = '';
  dictForm.name = '';
  dictForm.isEdit = '0';
  dictForm.grade = 0;
  dictForm.sx = 0;
  dictForm.value = '';
  dictForm.bz = '';
}

// 中间字段弹框保存
function saveDict(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (dictForm.id === null) {
      const url = '/api/sys/basDict/addDict';
      const user = {
        code: dictForm.code,
        name: dictForm.name,
        pid: dictForm.pid,
        grade: 0,
        sx: dictForm.sx,
        isEdit: dictForm.isEdit,
        bz: dictForm.bz,
        orgId: store.userInfo.orgId
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          if (res.status.code == 1) {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            clearForm();
            showDialog.value = false;
            findDictList();
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增字段失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/sys/basDict/editDict';
      const user = {
        id: dictForm.id,
        code: dictForm.code,
        name: dictForm.name,
        grade: 0,
        sx: dictForm.sx,
        isEdit: dictForm.isEdit,
        bz: dictForm.bz,
        orgId: dictForm.orgId
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          if (res.status.code == 1) {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            setTimeout(() => {
              clearForm();
              showDialog.value = false;
              findDictList();
            }, 500);
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('修改字段失败', VxeNotifyType.error);
        });
    }
  });
}

function getChildren(obj: any) {
  const children = obj.children;
  if (children.length > 0) {
    return getChildren(children[0]);
  } else {
    return obj;
  }
}

// 重置
function resetDictForm(row: any) {
  if (IsEmpty(row)) {
    clearForm();
    return;
  }
  dictForm.id = null;
  dictForm.pid = '';
  dictForm.orgId = '';
  dictForm.code = '';
  dictForm.name = '';
  dictForm.isEdit = '0';
  dictForm.grade = 0;
  dictForm.sx = 0;
  dictForm.value = '';
  dictForm.bz = '';
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#dictManage {
  height: 100%;
  .splitpanes {
    height: 100%;

    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    // 最左侧字典分类的树
    .sampleType {
      .tools-tree {
        min-width: 168px;
        padding: 0 5px 5px 5px;
        font-size: $font-size;
        border: none;
        .cirBtn {
          display: none;
          width: 16px;
          height: 16px;
          padding: 0px;
          margin-left: 10px;
        }
        .el-tree-node__content:hover {
          .cirBtn {
            display: inline-block !important;
          }
        }
      }
    }

    // 中间
    .tableBox {
      width: 100%;
      height: calc(100% - 40px);
      .spanIcon {
        padding: 0.1em 0.5em !important;
      }
    }
  }
}
</style>
